<template>
  <el-dialog
    :visible.sync="visible"
    :append-to-body="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="handleCancel"
    width="800px"
  >
    <template slot="title">
      <!-- <img src="@/assets/logo-min.png" alt=""> -->
      <span>选择共享范围</span>
    </template>
    <div class="field-select">
    <div class="left-part">
      <div class="total-box">
        <span>可选：</span>
        <div>
          <span :class="selectTotal > 0 ? 'activeNum' : '' "> {{ selectTotal }}</span>
          <span>/{{ treeOptions.length }}</span>
        </div>
      </div>
      <div class="content">
        <el-input
          size="small"
          placeholder="输入关键字进行过滤"
          v-model="filterText">
           <el-button size="small" slot="prepend" icon="el-icon-search"></el-button>
        </el-input>

        <el-tree
          class="filter-tree"
          show-checkbox
          :data="treeOptions"
          :props="defaultProps"
          node-key="id"
          default-expand-all
          :filter-node-method="filterNode"
          @check="getCheckedNodes"
          :default-checked-keys="defaultCheckedKeys"
          ref="tree">
          <span slot-scope="{ node, data }">
            <i class="el-icon-folder" v-if="node.childNodes.length"></i>
            <i class="el-icon-document" v-else></i>
            <span>{{ node.label }}</span>
          </span>
        </el-tree>
      </div>
    </div>

    <div class="left-part">
      <div class="total-box">
        <span>已选：</span>
        <span>{{ shareList.length }} 人</span>
      </div>
      <div class="content">
        <div
          class="content-right"
          v-for="(item, index) in shareList"
          :key="index"
        >
          <div>
            <!-- <img src="@/assets/logo-min.png" alt=""> -->
            <i class="el-icon-document"></i>
            <span>{{ item.label }}</span>
          </div>
          <i class="el-icon-close" @click="handleDelete(item)"></i>
        </div>
      </div>
    </div>
  </div>

  <div class="dialog-footer" slot="footer">
    <el-button @click="handleCancel">关闭</el-button>
    <el-button class="query-btn" @click="submitShareList">确定</el-button>
  </div>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      defaultCheckedKeys: [],
      filterText: '',
      treeOptions: [{
        id: 1,
        label: '一级 1',
        children: [{
          id: 4,
          label: '二级 1-1',
          children: [{
            id: 9,
            label: '三级 1-1-1'
          }, {
            id: 10,
            label: '三级 1-1-2'
          }]
        }]
      }, {
        id: 2,
        label: '一级 2',
        children: [{
          id: 5,
          label: '二级 2-1'
        }, {
          id: 6,
          label: '二级 2-2'
        }]
      }, {
        id: 3,
        label: '一级 3',
        children: [{
          id: 7,
          label: '二级 3-1'
        }, {
          id: 8,
          label: '二级 3-2'
        }]
      }],
      shareList: [
        // {
        //   label: '手机号',
        //   value: 'phone',
        //   selected: true,
        // },
        // {
        //   label: '创建时间',
        //   value: 'createTime',
        //   selected: true,
        // },
        // {
        //   label: '更新时间',
        //   value: 'updateTime',
        //   selected: true,
        // },
      ],
      selectTotal: 0,
      selectedTotal: 0,
      lastClickTime: 0, // 上次点击的时间戳
      doubleClickThreshold: 300, // 双击的阈值（毫秒）
    }
  },
  computed: {
    activeRight() {
      return this.treeOptions.some((item) => item.checked)
    },
    activeLeft() {
      return this.shareList.some((item) => item.checked)
    },
  },

  methods: {
    normalizeRole(node) {
      if(node.children && !node.children.length) {
       delete node.children
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children,
      }
    },
    handleCancel() {
      this.visible = false;   
      this.shareList = [];
      this.filterText = "";
      this.shareList = [];
      this.selectTotal = 0;
      this.selectedTotal = 0;
      this.$refs.tree.setCheckedKeys([]);
    },
    // 添加递归查找节点的方法
    findNodeById(tree, id) {
      for (const node of tree) {
        if (node.id === id) {
          return node;
        }
        if (node.children && node.children.length) {
          const foundNode = this.findNodeById(node.children, id);
          if (foundNode) {
            return foundNode;
          }
        }
      }
      return null;
    },
    handleOpen(val) {
      this.visible = true;
      this.shareList = [];
      this.defaultCheckedKeys = val;

      //  回显默认选中项
      this.defaultCheckedKeys.forEach(id => {
        const node = this.findNodeById(this.treeOptions, id);
        if (node) {
          this.shareList.push(this.normalizeRole(node));
        }
      });
      
      // 更新已选数量
      this.selectTotal = this.shareList.length;
      
      console.log(this.shareList);

    },
    submitShareList() {
      this.$emit('submitShareList', this.shareList);
      this.handleCancel();
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 设置已经选中的数据
    setChecedNodes() {
      this.$refs.tree.setCheckedNodes(this.shareList);
    },
    // 获取选中数据
    getCheckedNodes(data, checked, node) {
      // console.log(111, data, 222, checked, 333, node);
      // this.shareList = this.$refs.tree.getCheckedNodes();
      this.shareList = this.$refs.tree.getCheckedNodes()
        .filter(node => !node.children || node.children.length === 0);
      const childIds = this.getChildIds(data);

    },
    // 获取子节点的 ID
    getChildIds(node) {
      let ids = [];
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => {
          ids.push(child.id); // 获取子节点的 ID
          if (child.children && child.children.length > 0) { // 如果子节点还有子节点，递归获取
            ids = ids.concat(this.getChildIds(child));
          }
        });
      } else { // 没有子节点时直接返回当前节点的 ID（对于叶子节点）
        ids.push(node.id);
      }
      return ids;
    },
    handleDelete(item) {
      // 从shareList中移除该项
      this.shareList = this.shareList.filter((i) => i.id !== item.id);
      
      // 同步取消el-tree中对应节点的选中状态
      this.$refs.tree.setChecked(item.id, false);
    },

  },
}
</script>

<style lang="scss" scoped>
  
@import '@/assets/styles/newBase.scss';

  .field-select {
    display: flex;
    justify-content: space-between;
  }
  ::v-deep .el-dialog__header {
    color: #303133;
    font-size: 16px;
    font-weight: 500;
    display: flex;
    align-items: center;
    background: #F5F7FA;
    padding: 10px 16px !important;
  
    img {
      width: 30px;
      margin: 0 8px 0 0;
    }
  }

  .left-part {
    width: calc(50% - 15px);
    height: 430px;
    .content {
      height: 400px;
      overflow: auto;
      border: 1px solid #e4e7ed;
      border-radius: 0 0 4xp 4px;
      overflow: auto;
      padding: 10px;
      .el-input {
        width: 100%;
      }
    }
  }

  .el-tree .el-icon-folder {
    margin: 0 8px 0 0;
  }

  .el-tree .el-icon-document {
    margin: 0 8px 0 0;
  }

  .content-right {
    display: flex;
    align-items: center;
    align-items: center;
    justify-content: space-between;
    height: 35px;
    div {
      display: flex;
      align-items: center;
    }
    i {
      cursor: pointer;
    }
    img {
      width: 30px;
    }
  }
  .right-part {
    width: 45%;
  }
  .total-box {
    height: 30px;
    padding: 8px 10px;
    border-radius: 4px 4px 0 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #F5F7FA;
    border: 1px solid #EBEEF5 ;
  }
  .el-checkbox {
    width: 100px;
    padding: 2px 10px;
    border-radius: 3px;
    margin: 10px;
  }

  .el-icon-arrow-left, .el-icon-arrow-right {
    color: #FFF;
  }
  .activeNum {
    color: #2F6CED;
  }

</style>